import { search, suggestion } from '@/api'
import { SearchParams } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import {
  getLocalHistories,
  removeLocalHistories,
  setLocalHistories
} from '@/utils/auth'
// 搜索查询息的 action
function searchAction (q: string): RootThunkAction {
  return async dispatch => {
    const res = await suggestion(q)
    console.log(res)

    dispatch({ type: 'search/suggest', payload: res.data.data.options })
  }
}
// 保存搜索历史的 action
function saveHistoryAction (search: string): RootThunkAction {
  return async dispatch => {
    const _old = getLocalHistories()
    _old.push(search)
    const _new = [...new Set(_old)]
    setLocalHistories(_new)
    dispatch({ type: 'search/history', payload: _new })
  }
}
// 删除搜索历史的 action
function delHistoryAction (index: number): RootThunkAction {
  return async dispatch => {
    const _old = getLocalHistories()

    _old.splice(index, 1)
    setLocalHistories(_old)
    dispatch({ type: 'search/history', payload: _old })
  }
}
// 清空搜索历史的 action
function clearHistoryAction (): RootThunkAction {
  return async dispatch => {
    setLocalHistories([])
    dispatch({ type: 'search/history', payload: [] })
  }
}
// 搜索结果的 action
function searchResHistoryAction (params: SearchParams): RootThunkAction {
  return async dispatch => {
    const res = await search(params)
    console.log(res)

    dispatch({
      type: 'search/results',
      payload: {
        res: res.data.data.results,
        search_total: res.data.data.total_count
      }
    })
  }
}
// 清空搜索结果的 action
function clearResHistoryAction () {
  return { type: 'search/clear' }
}
export {
  searchAction,
  saveHistoryAction,
  delHistoryAction,
  clearHistoryAction,
  searchResHistoryAction,
  clearResHistoryAction
}
